package com.common.util;

import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.io.OutputStream;
import java.util.Random;

import javax.imageio.ImageIO;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

/**
 * 验证码
 * 2014-03-25
 */
@Controller
@RequestMapping("/SafeCode")
public class SafeCodeGenerator extends HttpServlet {

	private static final long serialVersionUID = 4654130670494432140L;

	public SafeCodeGenerator() {
		super();
	}
	
	@RequestMapping(value = "/getSafeCode")
	public void getSafeCode(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// 设置响应头 Content-type类型   
				response.setContentType("image/jpeg"); 
		        // 以下三句是用于设置页面不缓存   
				response.setHeader("Pragma", "No-cache");   
				response.setHeader("Cache-Control", "No-cache");   
				response.setDateHeader("Expires", 0);   
		  
				request.getSession().removeAttribute("safecode");
				
				int count_YZM = 4;
				//String coun = request.getParameter("count_YZM");
//				if(null != coun){
//					if(coun.trim().length() > 0){
//						count_YZM = Integer.parseInt(coun);
//					}
//				}
				
		        OutputStream os = response.getOutputStream();   
		        int width = 120, height = 37;  
		        if(6 == count_YZM){
		        	width = 120;
		        }
		        // 建立指定宽、高和BufferedImage对象   
		        BufferedImage image = new BufferedImage(width, height,BufferedImage.TYPE_INT_RGB);   
		  
		        Graphics g = image.getGraphics(); // 该画笔画在image上   
		        Color c = g.getColor(); // 保存当前画笔的颜色，用完画笔后要回复现场   
		        g.fillRect(0, 0, width, height);   
		           
		  
		        char[] ch = "abcdefghjkmnpqrstuvwxyz23456789".toCharArray(); // 随即产生的字符串 不包括 i l(小写L) o（小写O） 1（数字1）0(数字0)   
		        int length = ch.length; // 随即字符串的长度   
		        String sRand = ""; // 保存随即产生的字符串   
		        Random random = new Random();   
		        for (int i = 0; i < count_YZM; i++) {   
		            // 设置字体   
		            g.setFont(getFont());   
		            // 随即生成0-9的数字   
		            String rand = new Character(ch[random.nextInt(length)]).toString();   
		            sRand += rand;   
		            // 设置随机颜色   
		            g.setColor(new Color(random.nextInt(255), random.nextInt(255), random.nextInt(255)));   
		            g.drawString(rand, 20 * i, 25);   
		        }   
		        //产生随即干扰点   
		        for (int i = 0; i < 20; i++) {   
		            int x1 = random.nextInt(width);   
		            int y1 = random.nextInt(height);   
		            g.drawOval(x1, y1, 2, 2);   
		        }  
		        
		        g.setColor(c); // 将画笔的颜色再设置回去   
		        g.dispose();   
		  
		        //将验证码记录到session   
		        request.getSession().setAttribute("safecode", sRand.trim());   
		        // 输出图像到页面   
		        ImageIO.write(image, "JPEG", os); 
	}

	//产生随即的字体   
    private Font getFont() {   
        Random random = new Random();   
        Font font[] = new Font[5];   
        font[0] = new Font("Ravie", Font.PLAIN, 24);   
        //font[1] = new Font("Antique Olive Compact", Font.PLAIN, 24);   
        font[1] = new Font("微软雅黑", Font.BOLD, 24);   
        //font[2] = new Font("Wide Latin", Font.PLAIN, 24);   
        font[2] = new Font("Gill Sans Ultra Bold", Font.PLAIN, 24);   
        return font[random.nextInt(3)];   
    }   

	
//	public void doGet(HttpServletRequest request, HttpServletResponse response)
//			throws ServletException, IOException {
//
//		this.doPost(request, response);
//	}
//
//	public void doPost(HttpServletRequest request, HttpServletResponse response)
//			throws ServletException, IOException {
//
//		// 设置响应头 Content-type类型   
//		response.setContentType("image/jpeg");   
//        // 以下三句是用于设置页面不缓存   
//		response.setHeader("Pragma", "No-cache");   
//		response.setHeader("Cache-Control", "No-cache");   
//		response.setDateHeader("Expires", 0);   
//  
//		request.getSession().removeAttribute("safecode");
//		
//		int count_YZM = 4;
//		String coun = request.getParameter("count_YZM");
//		if(null != coun){
//			if(coun.trim().length() > 0){
//				count_YZM = Integer.parseInt(coun);
//			}
//		}
//		
//        OutputStream os = response.getOutputStream();   
//        int width = 83, height = 36;  
//        if(6 == count_YZM){
//        	width = 120;
//        }
//        // 建立指定宽、高和BufferedImage对象   
//        BufferedImage image = new BufferedImage(width, height,BufferedImage.TYPE_INT_RGB);   
//  
//        Graphics g = image.getGraphics(); // 该画笔画在image上   
//        Color c = g.getColor(); // 保存当前画笔的颜色，用完画笔后要回复现场   
//        g.fillRect(0, 0, width, height);   
//           
//  
//        char[] ch = "abcdefghjkmnpqrstuvwxyz23456789".toCharArray(); // 随即产生的字符串 不包括 i l(小写L) o（小写O） 1（数字1）0(数字0)   
//        int length = ch.length; // 随即字符串的长度   
//        String sRand = ""; // 保存随即产生的字符串   
//        Random random = new Random();   
//        for (int i = 0; i < count_YZM; i++) {   
//            // 设置字体   
//            g.setFont(getFont());   
//            // 随即生成0-9的数字   
//            String rand = new Character(ch[random.nextInt(length)]).toString();   
//            sRand += rand;   
//            // 设置随机颜色   
//            g.setColor(new Color(random.nextInt(255), random.nextInt(255), random.nextInt(255)));   
//            g.drawString(rand, 20 * i, 25);   
//        }   
//        //产生随即干扰点   
//        for (int i = 0; i < 20; i++) {   
//            int x1 = random.nextInt(width);   
//            int y1 = random.nextInt(height);   
//            g.drawOval(x1, y1, 2, 2);   
//        }  
//        
//        g.setColor(c); // 将画笔的颜色再设置回去   
//        g.dispose();   
//  
//        //将验证码记录到session   
//        request.getSession().setAttribute("safecode", sRand.trim());   
//        // 输出图像到页面   
//        ImageIO.write(image, "JPEG", os);   
//	} 

	public void destroy() {
		super.destroy(); 
	}
	
	public void init() throws ServletException {
		
	}
}
